<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" scroll :max-height="600">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading || supplyLoading"
    >
      <!-- 基础信息 -->
      <el-form-item label="计划编号" prop="planCode">
        <el-input v-model="formData.planCode" placeholder="请输入计划编号" readonly />
      </el-form-item>
      <el-form-item label="航班号" prop="flightNo">
        <el-select
          v-model="formData.flightNo"
          placeholder="请选择航班号"
          :readonly="formType !== 'create'"
          @change="handleFlightNoChange"
          clearable
          filterable
        >
          <el-option
            v-for="item in flightNoList"
            :key="item.flightNo"
            :label="item.flightNo"
            :value="item.flightNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属公司" prop="airlineComp">
        <el-select v-model="formData.airlineComp" placeholder="请选择所属航空公司">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PPLAN_AIRLINE_ID)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="起飞时间" prop="depTime">
        <el-time-picker
          v-model="formData.depTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="选择起飞时间"
          clearable
          class="!w-240px"
          readonly
        />
      </el-form-item>
      <el-form-item label="起飞地点" prop="depLoc">
        <el-input v-model="formData.depLoc" placeholder="请输入起飞地点" readonly />
      </el-form-item>
      <el-form-item label="降落地点" prop="arrLoc">
        <el-input v-model="formData.arrLoc" placeholder="请输入降落地点" readonly />
      </el-form-item>
      <el-form-item label="降落时间" prop="arrTime">
        <el-time-picker
          v-model="formData.arrTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="选择降落时间"
          clearable
          class="!w-240px"
          readonly
        />
      </el-form-item>
      <el-form-item label="预落时间" prop="preLandingTime">
        <el-time-picker
          v-model="formData.preLandingTime"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="选择预落时间"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="前舱数量" prop="frontCabinQty">
        <el-input v-model.number="formData.frontCabinQty" placeholder="请输入前舱数量" />
      </el-form-item>
      <el-form-item label="中舱数量" prop="middleCabinQty">
        <el-input v-model.number="formData.middleCabinQty" placeholder="请输入中舱数量" />
      </el-form-item>
      <el-form-item label="后舱数量" prop="rearCabinQty">
        <el-input v-model.number="formData.rearCabinQty" placeholder="请输入后舱数量" />
      </el-form-item>

      <!-- 舱位配置区域 -->
      <ContentWrap>
        <!-- 前舱配置 -->
        <div class="meal-config-block">
          <div class="block-title">前舱配置</div>
          <!-- 前舱机供品 -->
          <el-form-item label="机供品" prop="frontSupplys">
            <div>
              <div
                v-for="(item, index) in formData.frontSupplys"
                :key="item.id || index"
                class="flex mb-5px"
              >
                <el-select
                  placeholder="请选择机供品"
                  filterable
                  class="!w-240px"
                  v-model="item.supplyId"
                  :error="item.supplyIdError"
                  :disabled="!formData.flightNo"
                >
                  <el-option
                    v-for="supply in supplySimpleList"
                    :key="supply.id"
                    :label="supply.name"
                    :value="String(supply.id)"
                  />
                </el-select>
                <el-input
                  class="!w-160px"
                  v-model.number="item.supplyQty"
                  placeholder="数量"
                  :error="item.supplyQtyError"
                  :disabled="!formData.flightNo"
                >
                  <template #append>{{ unit(item.supplyId) }}</template>
                </el-input>
                <el-button
                  type="danger"
                  style="margin-left: 20px"
                  @click="removeItem(formData.frontSupplys, index)"
                  link
                  v-if="index != 0"
                  :disabled="!formData.flightNo"
                >
                  <Icon icon="ep:delete" class="mr-5px" />删除
                </el-button>
              </div>
              <el-button @click="addItem(formData.frontSupplys)" :disabled="!formData.flightNo">
                <Icon icon="ep:plus" class="mr-5px" />添加前舱机供品
              </el-button>
            </div>
          </el-form-item>
          <!-- 前舱服务用具 -->
          <el-form-item label="服务用具" prop="frontServices">
            <div>
              <div
                v-for="(item, index) in formData.frontServices"
                :key="item.id || index"
                class="flex mb-5px"
              >
                <el-select
                  placeholder="请选择服务用具"
                  filterable
                  class="!w-240px"
                  v-model="item.supplyId"
                  :error="item.supplyIdError"
                  :disabled="!formData.flightNo"
                >
                  <el-option
                    v-for="service in serviceSimpleList"
                    :key="service.id"
                    :label="service.name"
                    :value="String(service.id)"
                  />
                </el-select>
                <el-input
                  class="!w-160px"
                  v-model.number="item.supplyQty"
                  placeholder="数量"
                  :error="item.supplyQtyError"
                  :disabled="!formData.flightNo"
                >
                  <template #append>{{ unit(item.supplyId) }}</template>
                </el-input>
                <el-button
                  type="danger"
                  style="margin-left: 20px"
                  @click="removeItem(formData.frontServices, index)"
                  link
                  v-if="index != 0"
                  :disabled="!formData.flightNo"
                >
                  <Icon icon="ep:delete" class="mr-5px" />删除
                </el-button>
              </div>
              <el-button @click="addItem(formData.frontServices)" :disabled="!formData.flightNo">
                <Icon icon="ep:plus" class="mr-5px" />添加前舱服务用具
              </el-button>
            </div>
          </el-form-item>
          <!-- 前舱纺织品 -->
          <el-form-item label="纺织品" prop="frontTextiles">
            <div>
              <div
                v-for="(item, index) in formData.frontTextiles"
                :key="item.id || index"
                class="flex mb-5px"
              >
                <el-select
                  placeholder="请选择纺织品"
                  filterable
                  class="!w-240px"
                  v-model="item.supplyId"
                  :error="item.supplyIdError"
                  :disabled="!formData.flightNo"
                >
                  <el-option
                    v-for="textile in textileSimpleList"
                    :key="textile.id"
                    :label="textile.name"
                    :value="String(textile.id)"
                  />
                </el-select>
                <el-input
                  class="!w-160px"
                  v-model.number="item.supplyQty"
                  placeholder="数量"
                  :error="item.supplyQtyError"
                  :disabled="!formData.flightNo"
                >
                  <template #append>{{ unit(item.supplyId) }}</template>
                </el-input>
                <el-button
                  type="danger"
                  style="margin-left: 20px"
                  @click="removeItem(formData.frontTextiles, index)"
                  link
                  v-if="index != 0"
                  :disabled="!formData.flightNo"
                >
                  <Icon icon="ep:delete" class="mr-5px" />删除
                </el-button>
              </div>
              <el-button @click="addItem(formData.frontTextiles)" :disabled="!formData.flightNo">
                <Icon icon="ep:plus" class="mr-5px" />添加前舱纺织品
              </el-button>
            </div>
          </el-form-item>
        </div>

        <!-- 中舱配置 -->
        <div class="meal-config-block">
          <div class="block-title">中舱配置</div>
          <el-form-item label="机供品" prop="middleSupplys">
            <div>
              <div
                v-for="(item, index) in formData.middleSupplys"
                :key="item.id || index"
                class="flex mb-5px"
              >
                <el-select
                  placeholder="请选择机供品"
                  filterable
                  class="!w-240px"
                  v-model="item.supplyId"
                  :error="item.supplyIdError"
                  :disabled="!formData.flightNo"
                >
                  <el-option
                    v-for="supply in supplySimpleList"
                    :key="supply.id"
                    :label="supply.name"
                    :value="String(supply.id)"
                  />
                </el-select>
                <el-input
                  class="!w-160px"
                  v-model.number="item.supplyQty"
                  placeholder="数量"
                  :error="item.supplyQtyError"
                  :disabled="!formData.flightNo"
                >
                  <template #append>{{ unit(item.supplyId) }}</template>
                </el-input>
                <el-button
                  type="danger"
                  style="margin-left: 20px"
                  @click="removeItem(formData.middleSupplys, index)"
                  link
                  v-if="index != 0"
                  :disabled="!formData.flightNo"
                >
                  <Icon icon="ep:delete" class="mr-5px" />删除
                </el-button>
              </div>
              <el-button @click="addItem(formData.middleSupplys)" :disabled="!formData.flightNo">
                <Icon icon="ep:plus" class="mr-5px" />添加中舱机供品
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="服务用具" prop="middleServices">
            <div>
              <div
                v-for="(item, index) in formData.middleServices"
                :key="item.id || index"
                class="flex mb-5px"
              >
                <el-select
                  placeholder="请选择服务用具"
                  filterable
                  class="!w-240px"
                  v-model="item.supplyId"
                  :error="item.supplyIdError"
                  :disabled="!formData.flightNo"
                >
                  <el-option
                    v-for="service in serviceSimpleList"
                    :key="service.id"
                    :label="service.name"
                    :value="String(service.id)"
                  />
                </el-select>
                <el-input
                  class="!w-160px"
                  v-model.number="item.supplyQty"
                  placeholder="数量"
                  :error="item.supplyQtyError"
                  :disabled="!formData.flightNo"
                >
                  <template #append>{{ unit(item.supplyId) }}</template>
                </el-input>
                <el-button
                  type="danger"
                  style="margin-left: 20px"
                  @click="removeItem(formData.middleServices, index)"
                  link
                  v-if="index != 0"
                  :disabled="!formData.flightNo"
                >
                  <Icon icon="ep:delete" class="mr-5px" />删除
                </el-button>
              </div>
              <el-button @click="addItem(formData.middleServices)" :disabled="!formData.flightNo">
                <Icon icon="ep:plus" class="mr-5px" />添加中舱服务用具
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="纺织品" prop="middleTextiles">
            <div>
              <div
                v-for="(item, index) in formData.middleTextiles"
                :key="item.id || index"
                class="flex mb-5px"
              >
                <el-select
                  placeholder="请选择纺织品"
                  filterable
                  class="!w-240px"
                  v-model="item.supplyId"
                  :error="item.supplyIdError"
                  :disabled="!formData.flightNo"
                >
                  <el-option
                    v-for="textile in textileSimpleList"
                    :key="textile.id"
                    :label="textile.name"
                    :value="String(textile.id)"
                  />
                </el-select>
                <el-input
                  class="!w-160px"
                  v-model.number="item.supplyQty"
                  placeholder="数量"
                  :error="item.supplyQtyError"
                  :disabled="!formData.flightNo"
                >
                  <template #append>{{ unit(item.supplyId) }}</template>
                </el-input>
                <el-button
                  type="danger"
                  style="margin-left: 20px"
                  @click="removeItem(formData.middleTextiles, index)"
                  link
                  v-if="index != 0"
                  :disabled="!formData.flightNo"
                >
                  <Icon icon="ep:delete" class="mr-5px" />删除
                </el-button>
              </div>
              <el-button @click="addItem(formData.middleTextiles)" :disabled="!formData.flightNo">
                <Icon icon="ep:plus" class="mr-5px" />添加中舱纺织品
              </el-button>
            </div>
          </el-form-item>
        </div>

        <!-- 后舱配置 -->
        <div class="meal-config-block">
          <div class="block-title">后舱配置</div>
          <el-form-item label="机供品" prop="rearSupplys">
            <div>
              <div
                v-for="(item, index) in formData.rearSupplys"
                :key="item.id || index"
                class="flex mb-5px"
              >
                <el-select
                  placeholder="请选择机供品"
                  filterable
                  class="!w-240px"
                  v-model="item.supplyId"
                  :error="item.supplyIdError"
                  :disabled="!formData.flightNo"
                >
                  <el-option
                    v-for="supply in supplySimpleList"
                    :key="supply.id"
                    :label="supply.name"
                    :value="String(supply.id)"
                  />
                </el-select>
                <el-input
                  class="!w-160px"
                  v-model.number="item.supplyQty"
                  placeholder="数量"
                  :error="item.supplyQtyError"
                  :disabled="!formData.flightNo"
                >
                  <template #append>{{ unit(item.supplyId) }}</template>
                </el-input>
                <el-button
                  type="danger"
                  style="margin-left: 20px"
                  @click="removeItem(formData.rearSupplys, index)"
                  link
                  v-if="index != 0"
                  :disabled="!formData.flightNo"
                >
                  <Icon icon="ep:delete" class="mr-5px" />删除
                </el-button>
              </div>
              <el-button @click="addItem(formData.rearSupplys)" :disabled="!formData.flightNo">
                <Icon icon="ep:plus" class="mr-5px" />添加后舱机供品
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="服务用具" prop="rearServices">
            <div>
              <div
                v-for="(item, index) in formData.rearServices"
                :key="item.id || index"
                class="flex mb-5px"
              >
                <el-select
                  placeholder="请选择服务用具"
                  filterable
                  class="!w-240px"
                  v-model="item.supplyId"
                  :error="item.supplyIdError"
                  :disabled="!formData.flightNo"
                >
                  <el-option
                    v-for="service in serviceSimpleList"
                    :key="service.id"
                    :label="service.name"
                    :value="String(service.id)"
                  />
                </el-select>
                <el-input
                  class="!w-160px"
                  v-model.number="item.supplyQty"
                  placeholder="数量"
                  :error="item.supplyQtyError"
                  :disabled="!formData.flightNo"
                >
                  <template #append>{{ unit(item.supplyId) }}</template>
                </el-input>
                <el-button
                  type="danger"
                  style="margin-left: 20px"
                  @click="removeItem(formData.rearServices, index)"
                  link
                  v-if="index != 0"
                  :disabled="!formData.flightNo"
                >
                  <Icon icon="ep:delete" class="mr-5px" />删除
                </el-button>
              </div>
              <el-button @click="addItem(formData.rearServices)" :disabled="!formData.flightNo">
                <Icon icon="ep:plus" class="mr-5px" />添加后舱服务用具
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="纺织品" prop="rearTextiles">
            <div>
              <div
                v-for="(item, index) in formData.rearTextiles"
                :key="item.id || index"
                class="flex mb-5px"
              >
                <el-select
                  placeholder="请选择纺织品"
                  filterable
                  class="!w-240px"
                  v-model="item.supplyId"
                  :error="item.supplyIdError"
                  :disabled="!formData.flightNo"
                >
                  <el-option
                    v-for="textile in textileSimpleList"
                    :key="textile.id"
                    :label="textile.name"
                    :value="String(textile.id)"
                  />
                </el-select>
                <el-input
                  class="!w-160px"
                  v-model.number="item.supplyQty"
                  placeholder="数量"
                  :error="item.supplyQtyError"
                  :disabled="!formData.flightNo"
                >
                  <template #append>{{ unit(item.supplyId) }}</template>
                </el-input>
                <el-button
                  type="danger"
                  style="margin-left: 20px"
                  @click="removeItem(formData.rearTextiles, index)"
                  link
                  v-if="index != 0"
                  :disabled="!formData.flightNo"
                >
                  <Icon icon="ep:delete" class="mr-5px" />删除
                </el-button>
              </div>
              <el-button @click="addItem(formData.rearTextiles)" :disabled="!formData.flightNo">
                <Icon icon="ep:plus" class="mr-5px" />添加后舱纺织品
              </el-button>
            </div>
          </el-form-item>
        </div>
      </ContentWrap>

      <!-- 其他字段 -->
      <el-form-item label="特殊说明" prop="remarks">
        <el-input
          type="textarea"
          :rows="2"
          v-model="formData.remarks"
          placeholder="请输入特殊说明"
        />
      </el-form-item>
      <el-form-item label="标记状态" prop="markStatus">
        <el-select v-model="formData.markStatus" placeholder="请选择生产状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PPLAN_PRODUCE_MARK_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生产状态" prop="status">
        <el-select v-model="formData.status" placeholder="请选择生产状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PPLAN_PRODUCE_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading || supplyLoading"
        >确 定</el-button
      >
      <el-button @click="dialogVisible = false" :disabled="supplyLoading">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { OnboardProducePlanApi, OnboardProducePlanVO } from '@/api/acm/onboardproduceplan'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { OnboardSupplyApi, OnboardSupplyVO } from '@/api/acm/onboardsupply'
import { computed, watch } from 'vue'

defineOptions({ name: 'OnboardProducePlanForm' })

const { t } = useI18n()
const message = useMessage()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const supplyLoading = ref(false)
const formType = ref('')

// 定义列表项接口类型
interface SupplyItem {
  supplyId: string
  supplyQty: number
  supplyIdError?: string
  supplyQtyError?: string
  [key: string]: any
}

interface ServiceItem extends SupplyItem {}
interface TextileItem extends SupplyItem {}

// 表单数据结构
const formData = ref<
  OnboardProducePlanVO & {
    frontSupplys: SupplyItem[]
    middleSupplys: SupplyItem[]
    rearSupplys: SupplyItem[]
    frontServices: ServiceItem[]
    middleServices: ServiceItem[]
    rearServices: ServiceItem[]
    frontTextiles: TextileItem[]
    middleTextiles: TextileItem[]
    rearTextiles: TextileItem[]
  }
>({
  id: undefined,
  planCode: undefined,
  flightNo: undefined,
  airlineComp: undefined,
  depTime: undefined,
  depLoc: undefined,
  depIata: undefined,
  arrLoc: undefined,
  arrIata: undefined,
  arrTime: undefined,
  preLandingTime: undefined,
  flightType: undefined,
  airlineType: undefined,
  frontCabinQty: undefined,
  middleCabinQty: undefined,
  rearCabinQty: undefined,
  remarks: undefined,
  markStatus: undefined,
  status: undefined,
  frontSupplys: [{ supplyId: '', supplyQty: 0 }],
  middleSupplys: [{ supplyId: '', supplyQty: 0 }],
  rearSupplys: [{ supplyId: '', supplyQty: 0 }],
  frontServices: [{ supplyId: '', supplyQty: 0 }],
  middleServices: [{ supplyId: '', supplyQty: 0 }],
  rearServices: [{ supplyId: '', supplyQty: 0 }],
  frontTextiles: [{ supplyId: '', supplyQty: 0 }],
  middleTextiles: [{ supplyId: '', supplyQty: 0 }],
  rearTextiles: [{ supplyId: '', supplyQty: 0 }]
})

// 表单验证规则
const validateSupplyList = (rule: any, list: SupplyItem[], callback: any) => {
  list.forEach((item) => {
    item.supplyIdError = ''
    item.supplyQtyError = ''
  })

  if (!list || list.length === 0) {
    return callback(new Error('请至少添加一条机供品数据'))
  }

  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    if (!item.supplyId) {
      item.supplyIdError = '请选择机供品'
      return callback(new Error(`第${i + 1}行机供品不能为空`))
    }
    if (item.supplyQty === undefined || item.supplyQty <= 0) {
      item.supplyQtyError = '数量必须大于0'
      return callback(new Error(`第${i + 1}行机供品数量必须大于0`))
    }
  }

  callback()
}

const validateServiceList = (rule: any, list: ServiceItem[], callback: any) => {
  list.forEach((item) => {
    item.supplyIdError = ''
    item.supplyQtyError = ''
  })

  if (!list || list.length === 0) {
    return callback(new Error('请至少添加一条服务用具数据'))
  }

  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    if (!item.supplyId) {
      item.supplyIdError = '请选择服务用具'
      return callback(new Error(`第${i + 1}行服务用具不能为空`))
    }
    if (item.supplyQty === undefined || item.supplyQty <= 0) {
      item.supplyQtyError = '数量必须大于0'
      return callback(new Error(`第${i + 1}行服务用具数量必须大于0`))
    }
  }

  callback()
}

const validateTextileList = (rule: any, list: TextileItem[], callback: any) => {
  list.forEach((item) => {
    item.supplyIdError = ''
    item.supplyQtyError = ''
  })

  if (!list || list.length === 0) {
    return callback(new Error('请至少添加一条纺织品数据'))
  }

  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    if (!item.supplyId) {
      item.supplyIdError = '请选择纺织品'
      return callback(new Error(`第${i + 1}行纺织品不能为空`))
    }
    if (item.supplyQty === undefined || item.supplyQty <= 0) {
      item.supplyQtyError = '数量必须大于0'
      return callback(new Error(`第${i + 1}行纺织品数量必须大于0`))
    }
  }

  callback()
}

const formRules = reactive({
  flightNo: [{ required: true, message: '航班号不能为空', trigger: 'blur' }],
  markStatus: [{ required: true, message: '标记状态不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '生产状态不能为空', trigger: 'change' }],
  frontSupplys: [{ required: true, validator: validateSupplyList, trigger: 'change' }],
  middleSupplys: [{ required: true, validator: validateSupplyList, trigger: 'change' }],
  rearSupplys: [{ required: true, validator: validateSupplyList, trigger: 'change' }],
  frontServices: [{ required: true, validator: validateServiceList, trigger: 'change' }],
  middleServices: [{ required: true, validator: validateServiceList, trigger: 'change' }],
  rearServices: [{ required: true, validator: validateServiceList, trigger: 'change' }],
  frontTextiles: [{ required: true, validator: validateTextileList, trigger: 'change' }],
  middleTextiles: [{ required: true, validator: validateTextileList, trigger: 'change' }],
  rearTextiles: [{ required: true, validator: validateTextileList, trigger: 'change' }]
})

const formRef = ref()

// 选择框数据源
const supplySimpleList = ref<OnboardSupplyVO[]>([]) // 机供品
const textileSimpleList = ref<OnboardSupplyVO[]>([]) // 纺织品
const serviceSimpleList = ref<OnboardSupplyVO[]>([]) // 服务用具

/** 统一调用接口获取不同类型的列表数据 */
const getSupplyListByType = async () => {
  const flightNo = formData.value.flightNo
  if (!flightNo) {
    supplySimpleList.value = []
    textileSimpleList.value = []
    serviceSimpleList.value = []
    return
  }

  supplyLoading.value = true
  try {
    const [supplyRes, textileRes, serviceRes] = await Promise.all([
      OnboardSupplyApi.getOnboardSupplySimpleList({
        categoryType: 1,
        name: '',
        flightNo
      }),
      OnboardSupplyApi.getOnboardSupplySimpleList({
        categoryType: 2,
        name: '',
        flightNo
      }),
      OnboardSupplyApi.getOnboardSupplySimpleList({
        categoryType: 3,
        name: '',
        flightNo
      })
    ])

    supplySimpleList.value = supplyRes
    textileSimpleList.value = textileRes
    serviceSimpleList.value = serviceRes

    if (supplyRes.length === 0 && textileRes.length === 0 && serviceRes.length === 0) {
      message.warning(`当前航班【${flightNo}】暂无配置数据，请先维护基础数据`)
    }
  } catch (err) {
    message.error('加载配置数据失败，请重试')
  } finally {
    supplyLoading.value = false
  }
}

/** 航班号变化时触发数据加载 */
const handleFlightNoChange = () => {
  getSupplyListByType()
}

/** 添加列表项 */
const addItem = (list: (SupplyItem | ServiceItem | TextileItem)[]) => {
  list.push({ supplyId: '', supplyQty: 0 })
}

/** 删除列表项 */
const removeItem = (list: any[], index: number) => {
  if (list.length > 1) {
    list.splice(index, 1)
  } else {
    message.warning('至少保留一条数据')
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  getSelectAllList()
  if (id) {
    formLoading.value = true
    try {
      const res = await OnboardProducePlanApi.getOnboardProducePlan(id)
      formData.value = {
        ...res,
        frontSupplys: res.frontSupplys?.length
          ? res.frontSupplys
          : [{ supplyId: '', supplyQty: 0 }],
        middleSupplys: res.middleSupplys?.length
          ? res.middleSupplys
          : [{ supplyId: '', supplyQty: 0 }],
        rearSupplys: res.rearSupplys?.length ? res.rearSupplys : [{ supplyId: '', supplyQty: 0 }],
        frontServices: res.frontServices?.length
          ? res.frontServices
          : [{ supplyId: '', supplyQty: 0 }],
        middleServices: res.middleServices?.length
          ? res.middleServices
          : [{ supplyId: '', supplyQty: 0 }],
        rearServices: res.rearServices?.length
          ? res.rearServices
          : [{ supplyId: '', supplyQty: 0 }],
        frontTextiles: res.frontTextiles?.length
          ? res.frontTextiles
          : [{ supplyId: '', supplyQty: 0 }],
        middleTextiles: res.middleTextiles?.length
          ? res.middleTextiles
          : [{ supplyId: '', supplyQty: 0 }],
        rearTextiles: res.rearTextiles?.length ? res.rearTextiles : [{ supplyId: '', supplyQty: 0 }]
      }
      await getSupplyListByType()
    } catch (err) {
      message.error('加载表单数据失败，请重试')
    } finally {
      formLoading.value = false
    }
  } else {
    supplySimpleList.value = []
    textileSimpleList.value = []
    serviceSimpleList.value = []
  }
}
defineExpose({ open })

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  try {
    await formRef.value.validate()

    formLoading.value = true
    const data = formData.value as unknown as OnboardProducePlanVO

    if (formType.value === 'create') {
      await OnboardProducePlanApi.createOnboardProducePlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await OnboardProducePlanApi.updateOnboardProducePlan(data)
      message.success(t('common.updateSuccess'))
    }

    dialogVisible.value = false
    emit('success')
  } catch (e) {
    if (typeof e === 'string') {
      message.error(e)
    } else if (e instanceof Error) {
      message.error(e.message)
    } else {
      message.error('存在内容为空的数据')
    }
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planCode: undefined,
    flightNo: undefined,
    airlineComp: undefined,
    depTime: undefined,
    depLoc: undefined,
    depIata: undefined,
    arrLoc: undefined,
    arrIata: undefined,
    arrTime: undefined,
    preLandingTime: undefined,
    flightType: undefined,
    airlineType: undefined,
    frontCabinQty: undefined,
    middleCabinQty: undefined,
    rearCabinQty: undefined,
    remarks: undefined,
    markStatus: undefined,
    status: undefined,
    frontSupplys: [{ supplyId: '', supplyQty: 0 }],
    middleSupplys: [{ supplyId: '', supplyQty: 0 }],
    rearSupplys: [{ supplyId: '', supplyQty: 0 }],
    frontServices: [{ supplyId: '', supplyQty: 0 }],
    middleServices: [{ supplyId: '', supplyQty: 0 }],
    rearServices: [{ supplyId: '', supplyQty: 0 }],
    frontTextiles: [{ supplyId: '', supplyQty: 0 }],
    middleTextiles: [{ supplyId: '', supplyQty: 0 }],
    rearTextiles: [{ supplyId: '', supplyQty: 0 }]
  }
  formRef.value?.resetFields()
}

// 监听弹窗关闭，清空状态
watch(dialogVisible, (isVisible) => {
  if (!isVisible) {
    supplyLoading.value = false
    supplySimpleList.value = []
    textileSimpleList.value = []
    serviceSimpleList.value = []
  }
})

/** 获取航机号列表 */
const flightNoList = ref([]) // 初始化为空数组，避免undefined
const getSelectAllList = async () => {
  try {
    const res = await OnboardSupplyApi.getSelectAll()
    if (!Array.isArray(res)) {
      flightNoList.value = []
      return
    }

    // 1. 定义一个Set用于存储已出现的flightNo（利用Set的唯一性）
    const flightNoSet = new Set<string>()
    // 2. 定义去重后的数组
    const uniqueList: { flightNo: string }[] = []

    res.forEach((item) => {
      // 过滤无效的flightNo（如undefined、null、空字符串）
      if (!item?.flightNo) return

      const currentFlightNo = item.flightNo
      // 3. 若Set中不存在当前flightNo，则添加到数组和Set中
      if (!flightNoSet.has(currentFlightNo)) {
        flightNoSet.add(currentFlightNo)
        uniqueList.push({ flightNo: currentFlightNo })
      }
    })

    console.log('去重后的列表：', uniqueList)
    flightNoList.value = uniqueList // 赋值去重后的数组
  } catch (error) {
    flightNoList.value = [] // 出错时置空，避免异常
  }
}

/**
 * 计算规格单位：根据物品ID从机供品、服务用具、纺织品列表中匹配对应规格
 * @param id 物品ID（字符串/数字类型）
 * @returns 规格单位（如“个”“套”“件”），未匹配到时返回空字符串
 */
const unit = computed(() => {
  return (id: string | number) => {
    // 统一ID为字符串类型，避免类型不匹配导致查找失败
    const targetId = String(id)
    // 优先从当前可能的列表中查找（按业务场景优先级排序）
    const matchItem =
      supplySimpleList.value.find((item) => String(item.id) === targetId) ||
      serviceSimpleList.value.find((item) => String(item.id) === targetId) ||
      textileSimpleList.value.find((item) => String(item.id) === targetId)
    // 返回规格单位，若不存在则返回空字符串
    return matchItem?.standardName || ''
  }
})
</script>

<style scoped>
.meal-config-block {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.block-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #1d2129;
}
.flex {
  display: flex;
  align-items: center;
}
.mb-5px {
  margin-bottom: 5px;
}
</style>
